package com.zz.tijian.config;

import lombok.Data;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
@ConfigurationProperties(prefix = "es")
@Data
public class EsConfig {
    private String ip;
    private int port;

    @Bean
    public RestHighLevelClient client(){

        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost(ip,port,"http")
                ).setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
                    @Override
                    public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
                        return requestConfigBuilder.setConnectTimeout(90000000)//25hours
                                .setSocketTimeout(90000000);
                    }
                }).setHttpClientConfigCallback((httpAsyncClientBuilder -> {
                    httpAsyncClientBuilder.disableAuthCaching();//禁用身份验证缓存
                    //显式设置keepAliveStrategy
                    httpAsyncClientBuilder.setKeepAliveStrategy((httpResponse,httpContext) -> TimeUnit.MINUTES.toMillis(3));
                    //显式开启tcp keepalive
                    httpAsyncClientBuilder.setDefaultIOReactorConfig(IOReactorConfig.custom().setSoKeepAlive(true).build());
                    return httpAsyncClientBuilder;
                }))
        );
        return client;
    }
}
